package com.gf.snoopy.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gf.snoopy.dto.CompanyDto;
import com.gf.snoopy.dto.SubProjectDto;
import com.gf.snoopy.platform.exception.PokeErrorCode;
import com.gf.snoopy.platform.exception.PokeException;
import com.gf.snoopy.platform.result.PokeResult;
import com.gf.snoopy.service.CompanyService;
import com.gf.snoopy.util.AoDataPage;
import com.gf.snoopy.util.ConvertUtil;
import com.gf.snoopy.util.SnoopyUtil;
import com.gf.snoopy.util.page.Page;
import com.gf.snoopy.util.page.PagedList;

@Controller
@RequestMapping("/company")
public class CompanyController {

	@Resource
	private CompanyService companyService;
	
	/**
	 * 分页获取机构详情
	 * @param voteId
	 * @param aoData
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/showPage")
	@ResponseBody	
	public String getProjectPage(Integer projectId,String aoData) throws Exception{
		if(aoData==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		AoDataPage aoDataPage = SnoopyUtil.parseAoData(aoData);
		Page page = new Page();
		page.setOffset(aoDataPage.offset);
		page.setPageSize(aoDataPage.pageSize);
		CompanyDto dto = new CompanyDto();
		dto.setName(aoDataPage.search);
		PagedList<CompanyDto> companyDtos = companyService.getProjectPage(dto, page);
		return PokeResult.getPokeResultSuccess(SnoopyUtil.constructPageResult(companyDtos));
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public String saveOrUpateProject(@RequestBody String jsonPorject) throws Exception{
		if(jsonPorject==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM);
		}
		CompanyDto dto = ConvertUtil.convertJsonToBean(jsonPorject,CompanyDto.class);
		if(dto.getId()==null){
			companyService.save(dto);
		}else{
			companyService.update(dto);
		}
		return PokeResult.getPokeResultSuccess(SnoopyUtil.SUCCESS);
	}
	
	/**
	 * 根据Id查找结果
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/find")
	@ResponseBody
	public String findById(Integer id) throws Exception{
		CompanyDto result = companyService.findById(id);
		return PokeResult.getPokeResultSuccess(result);
	}
	
	/**
	 * 根据Id删除结果
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	@ResponseBody
	public String deleteById(Integer id) throws Exception{
		companyService.deleteById(id);
		return PokeResult.getPokeResultSuccess(SnoopyUtil.SUCCESS);
	}
	
	/**
	 * 查询所有机构
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/findAll")
	@ResponseBody
	public String findAllSubProject() throws Exception{
		List<CompanyDto> dtos = companyService.findAllCompany();
		return PokeResult.getPokeResultSuccess(dtos);
	}
	
}
